<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>4-拖拽类.html</title>
    <style>
      #box {
        position: absolute;
        left: 0;
        top: 0;
        width: 100px;
        height: 100px;
        background: red;
        cursor: pointer;
      }
      #box2 {
        position: absolute;
        left: 100px;
        top: 0;
        width: 100px;
        height: 100px;
        background: green;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div id="box"></div>
    <div id="box2"></div>
    <script>
      class Drag {
        constructor(el) {
          this.el = el;
          this.startMouse = {}; // 按下时，鼠标坐标
          this.startOffset = {}; // 按下时，元素坐标
          let move = e => {
            this.move(e)
          }
          this.el.addEventListener("mousedown",(e)=>{
            this.start(e)
            document.addEventListener("mousemove", move);
            document.addEventListener(
              "mouseup",
              () => {
                document.removeEventListener("mousemove", move);
              },
              { once: true }
            );
          })
        }
        start(e) {
          this.startMouse = {
            x: e.clientX,
            y: e.clientY,
          };
          this.startOffset = {
            x: parseFloat(getComputedStyle(this.el)["left"]),
            y: parseFloat(getComputedStyle(this.el)["top"]),
          };
        }
        move(e) {
          let nowMouse = {
            x: e.clientX,
            y: e.clientY,
          };
          let dis = {
            x: nowMouse.x - this.startMouse.x,
            y: nowMouse.y - this.startMouse.y,
          };
          let nowOffset = {
            x: dis.x + this.startOffset.x,
            y: dis.y + this.startOffset.y,
          };
          this.el.style.left = nowOffset.x + "px";
          this.el.style.top = nowOffset.y + "px";
        }
      }
      let box = document.querySelector('#box')
      let boxDrag = new Drag(box)

      let box2 = document.querySelector('#box2')
      let box2Drag = new Drag(box2)
    </script>
  </body>
</html>
